<?php

include_once('ligature/comment.class.php');
include_once('ligature/markdown.php');

class Ligature_Comment_model extends Model{
    
    function Ligature_Comment_model() {
        parent::Model();
    }
    
    /**
     *  Persist a new Comment in the database.
     *  @param integer $userId Comment author's user ID
     *  @param integer $postId Post ID
     *  @param string $comment The comment text
     *  @return integer New comment's unique identifier
     */
    function createComment($userId, $postId, $comment) {
        
        $data = array(
                'postId' => $postId,
                'authorId' => $userId,
                'comment' => $comment,
                'dateCreated' => time()
            );
        
        $this->db->insert('ligature_comment', $data);
        
        return $this->db->insert_id();
    }
    
    function tweetComment($postId, $postAuthorScreenName, $commentId, $commentText) {

		$twitter = new EpiTwitter(
                $this->config->item('twitter_consumer_key', 'ligature'),
                $this->config->item('twitter_consumer_secret', 'ligature'),
                $this->session->userdata('oauth_token'),
                $this->session->userdata('oauth_token_secret')
			);
		
		$replyTo = '@' . $postAuthorScreenName . ' ';
		$postShortUrl = ' ' . site_url('p/' . $postId);
		$commentLength = 140 - (strlen($replyTo) + strlen($postShortUrl));
		
		$shortComment = strip_tags($this->input->post('comment'));
		
		if (strlen($shortComment) > $commentLength) {
			$shortComment = substr($shortComment, 0, ($commentLength - 3)) . '...';
		}
		
		log_message('debug', '%%%%%%%%%%% ' . $replyTo . $shortComment . $postShortUrl);
		
		$response = $twitter->post_statusesUpdate(array(
				'status' =>  $replyTo . $shortComment . $postShortUrl
			));
        
        /*
            If the comment author is an admin, we need to store the tweet's ID
            so we don't display it in the main feed.
        */
        if (in_array($postAuthorScreenName, $this->config->item('admins', 'ligature'))) {
            $newTweetId = $response->id;
            $sql = 'INSERT IGNORE INTO ligature_admin_tweet (tweetId) VALUES (?)';
            $this->db->query($sql, array($newTweetId));
        }
    }

    /**
     *  Retrieve an Comment from the database using its identifier.
     *  @param mixed $id Comment's unique identifier
     *  @return Comment
     */
    function readComment($id) {
        $comment = new Comment();

        // TODO: Retrieve Comment from data source

        // TODO: Populate $comment fields
        $comment->setCommentId('');
        $comment->setPostTitle('');
        $comment->setPostSlug('');
        $comment->setAuthorName('');
        $comment->setAuthorTwitterScreenName('');
        $comment->setComment('');
        $comment->setDateCreated('');

        return $comment;
    }
    
    /**
     *  Retrieve an array of Comment objects.
     *  @param integer $page Which batch of results to display
     *  @param integer $perPage Number of Comment objects to return in batch, 0 for all
     *  @return array
     */
    function listComment($page = 1, $perPage = 0) {
        
		$comments = array();
		
        $this->db->select('ligature_comment.id, ligature_post.id as postId, ligature_user.name, ligature_user.twitterScreenName, ligature_comment.comment, ligature_comment.dateCreated, ligature_post.title, ligature_post.slug');
        $this->db->from('ligature_comment');
        $this->db->join('ligature_user', 'ligature_comment.authorId = ligature_user.id');
		$this->db->join('ligature_post', 'ligature_comment.postId = ligature_post.id');
		$this->db->order_by('dateCreated', 'desc');
        if ($perPage > 0) {
            $this->db->limit($perPage, (($page - 1) * $perPage));
		}
        
		$query = $this->db->get();
        
		// Create and populate Comment instances
        /* $commentId = null, $postId = null, $postTitle = null, $postSlug = null, $authorId = null, $authorName = null, $authorTwitterScreenName = null, $comment = null, $dateCreated = null, $dateCreatedLocal = null */
        foreach ($query->result() as $row) {
            $comments[] = new Comment(
                    $row->id,
                    $row->postId,
                    $row->title,
                    $row->slug,
                    null,
                    $row->name,
                    $row->twitterScreenName,
                    $row->comment,
                    $row->dateCreated,
                    $this->clickframes->formatLocalTime($row->dateCreated, $this->config->item('timezone', 'ligature'))
                );
        }
		
        return $comments;
    }
    
    
    function listCommentsForPost($id) {
        $comments = array();
        
        // Retrieve all Posts from data source
        $this->db->select('ligature_comment.id, ligature_user.name, ligature_user.twitterScreenName, ligature_comment.comment, ligature_comment.dateCreated');
        $this->db->from('ligature_comment');
        $this->db->join('ligature_user', 'ligature_comment.authorId = ligature_user.id');
		$this->db->where('ligature_comment.postId', $id);
        
        $query = $this->db->get();
        // Create and populate Post instances
        foreach ($query->result() as $row) {
            $comments[] = new Comment(
                    $row->id,
                    $id,
                    null,
                    null,
                    null,
                    $row->name,
                    $row->twitterScreenName,
                    $row->comment,
                    $row->dateCreated,
                    $this->clickframes->formatLocalTime($row->dateCreated, $this->config->item('timezone', 'ligature'))
                );
        }
        
        return $comments;
    }
    
    /**
     *  Retrieve an array of Comment objects which match the provided
     *  search terms.
     *  @param string $searchTerms Search terms to match
     *  @return array
     */
    function searchComment($searchTerms) {
        // TODO: Retrieve all matching Comments from data source
        // TODO: Create and populate Comment instances
        return array();        
    }
    
    /**
     *  Update an existing Comment in the database. 
     *  @param Comment $comment The updated object.
     *  @return boolean Returns true if update successful.
     */
    function updateComment($comment) {
        // TODO: Update Comment in data source
        return true;
    }
    
    /**
     *  Delete an Comment from the database.
     *  @param mixed $id Unique identifier of Comment to delete
     *  @return boolean Returns true if delete successful.
     */
    function deleteComment($id) {
        // TODO: Remove Comment from data source
        return true;
    }
    
}

/* clickframes::version=2264226640::clickframes */
?>